package com.hs.httpclient.service;

import com.hs.httpclient.listener.DownCallBack;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;
import java.util.Set;

/**
 * @Author: songhao
 * @Date: 2020/11/12
 * @Description: 抽象类
 */
public abstract class AbstractHttpRequest implements HttpService{

    static final Logger logger = LoggerFactory.getLogger(AbstractHttpRequest.class);

    @Override
    public String requestGet(String url, Map<String, String> headerMap) throws Exception {
        throw new Exception("不支持Get请求");
    }

    @Override
    public String requestPostByForm(String url, Map<String, String> headerMap, Map<String, Object> paramMap) throws Exception {
        throw new Exception("不支持Post请求");
    }

    @Override
    public void download(String url, String filePath, Map<String, String> headMap, DownCallBack progress) throws Exception{
        logger.info("===>正在请求url:{}",url);
        CloseableHttpClient httpclient = null;
        try {
            httpclient = HttpClients.createDefault();
            HttpGet httpGet = new HttpGet(url);
            setRequestHead(httpGet, headMap);
            CloseableHttpResponse response1 = httpclient.execute(httpGet);
            try {
                logger.info("响应状态为:{}",response1.getStatusLine());
                HttpEntity httpEntity = response1.getEntity();
                long contentLength = httpEntity.getContentLength();
                logger.info("响应长度为:{}",contentLength);
                InputStream is = httpEntity.getContent();
                // 根据InputStream 下载文件
                ByteArrayOutputStream output = new ByteArrayOutputStream();
                byte[] buffer = new byte[4096];
                int r = 0;
                long totalRead = 0;
                while ((r = is.read(buffer)) > 0) {
                    output.write(buffer, 0, r);
                    totalRead += r;
                    if (progress != null) {// 回调进度
                        progress.onProgress((int) (totalRead * 100 / contentLength));
                    }
                }
                FileOutputStream fos = new FileOutputStream(filePath);
                output.writeTo(fos);
                output.flush();
                output.close();
                fos.close();
                EntityUtils.consume(httpEntity);
            } finally {
                response1.close();
            }
        } catch (Exception e) {
            throw e;
        } finally {
            try {
                if(httpclient != null){
                    httpclient.close();
                }
            } catch (IOException e) {
                throw e;
            }
        }
    }

    /**
     * 设置http的HEAD
     * @param httpRequestBase
     * @param headMap
     */
    protected static void setRequestHead(HttpRequestBase httpRequestBase, Map<String, String> headMap) {
        if (headMap != null && headMap.size() > 0) {
            Set<String> keySet = headMap.keySet();
            for (String key : keySet) {
                httpRequestBase.addHeader(key, headMap.get(key));
            }
        }
    }
}
